# -*- coding: utf-8 -*-
from setting.mysql_test import mysql45_config
import pymysql
from utils.msg_queue import connect_message_queue
from setting.redis_config import redis_embed_url

REDIS_PASSWORD = None


class EmbedDataConsume(object):
    def __init__(self):
        self.mysql_conn = pymysql.connect(**mysql45_config)
        self.mysql_cursor = self.mysql_conn.cursor()
        self.redis_url = redis_embed_url

    def put_redis(self, queue_name, json_msg):
        #避免openAI的接口不稳定导致的数据丢失，将数据存入redis，控制速度如果失败重新入队
        #生产写入数据
        p = connect_message_queue(queue_name, url=self.redis_url, maxsize=10000, lazy_limit=True)
        p.put(json_msg)

    # def dictinct_mysql(self, image_id):
    #     #判断图片是否已经成功获得embed，如果成功则跳过
    #     sql = 'select embeddings_labels from image_info where id = %s' % (image_id)
    #     self.mysql_cursor.execute(sql)
    #     embed_content = self.mysql_cursor.fetchone()
    #     if embed_content:
    #         print('图片嵌入数据已存在，跳过')
    #         return False
    #     else:
    #         return True

    def save_mysql(self, embed_data, image_id):
        #保存数据到mysql
        print('image_id和embed_data', embed_data, image_id)
        insert_embed_sql = "update image_info set embeddings_labels='%s',update_on = NOW() where id='%s'" % (embed_data, image_id)
        self.mysql_cursor.execute(insert_embed_sql)
        self.mysql_conn.commit()
        print('save mysql success')

    def run(self, queue_name):
        o = connect_message_queue(queue_name, url=self.redis_url, maxsize=10000, lazy_limit=True)
        while o.qsize() > 0:
            save_data = o.get()
            if not save_data:
                print('save_data is empty')
                return
            embed_data = save_data.get('tag_embedding')
            image_id = save_data.get('id')
            #判断图片embed是否写入，如果成功则跳过
            # result = self.dictinct_mysql(image_id)
            # if not result:
            #     continue
            try:
                self.save_mysql(embed_data, image_id)
            except Exception as e:
                print('save_mysql error:', e)
                retry_mysql_queue_name = queue_name + '_retry_mysql'
                self.put_redis(retry_mysql_queue_name, save_data)
                continue


if __name__ == '__main__':
    queue_name = 'tag_embed_data'
    consume = EmbedDataConsume()
    consume.run(queue_name)

